package app.fugema.shop.main.setting.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;

import com.base.common.app.LoginUtils;
import com.base.common.model.bean.ADInfo;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.SPUtils;
import com.base.common.utils.UIUtils;
import com.base.common.view.adapter.MyFlexboxLayoutManager;
import com.base.common.view.adapter.MyGridLayoutManager;
import com.base.common.view.adapter.MyLinearLayoutManager;
import com.base.common.view.adapter.connector.OnItemClickInterface;
import com.base.common.view.base.BaseActivity;
import com.base.common.view.base.OnGetDataListener;
import com.base.common.view.widget.RecyclerViewPPW;
import com.base.common.viewmodel.BaseViewObserver;

import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.databinding.HomeSearchActivityBinding;
import app.fugema.shop.main.goods.model.CateGoodsPageBean;
import app.fugema.shop.main.goods.model.GoodsSearchParams;
import app.fugema.shop.main.home.adapter.HomeSearchDrawerAdapter;
import app.fugema.shop.main.home.adapter.HomeSearchGoodsAdapter;
import app.fugema.shop.main.home.adapter.SearchAdapter;
import app.fugema.shop.main.home.model.HotSearchBean;
import app.fugema.shop.main.home.model.SearchGoodsBean;
import app.fugema.shop.main.home.vm.SearchVM;

import java.util.ArrayList;
import java.util.List;

//搜索页面
public class SearchActivity extends BaseActivity<HomeSearchActivityBinding, SearchVM> implements OnGetDataListener, OnItemClickInterface {
    private String userKey = "";

    public static void start(Context context) {
        context.startActivity(new Intent(context, SearchActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_search_activity);
    }

    private SearchAdapter adapterHistory, adapterHot;
    private HomeSearchGoodsAdapter goodsAdapter;
    private HomeSearchDrawerAdapter drawerAdapter;//抽屉的适配器
    private RecyclerViewPPW ppwDefault;//默认的下拉弹窗

    private int sort = 1;//排序  （1：默认，2：销量，3：价格，4：评论数，5：上架时间）

    private int orderBy = 1;//排序(1升序 2降序)


    private boolean isFirstLoading = true;//是否是首次加载

    private GoodsSearchParams searchParams;

    @Override
    protected void initView() {
        super.initView();
        if (LoginUtils.isLogin()) {
            userKey = LoginUtils.getToken();
        }
        searchParams = new GoodsSearchParams();
        binding.ivBack.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                finish();
            }
        });
        binding.tvSearch.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                String text = binding.etSelectText.getText().toString().trim();
                if (UIUtils.isNotEmpty(text)) {
                    HotSearchBean.DataBean dataBean = new HotSearchBean.DataBean();
                    dataBean.setTitle(text);
                    addHistory(dataBean);
                    onGetData(1);
                } else {
                    UIUtils.showToastSafes("请输入需要搜索的商品");
                }

            }
        });

        binding.givDelete.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                clearHistory();
            }
        });
        binding.rvHistoryRecycler.setLayoutManager(new MyFlexboxLayoutManager(getActivity()));
        adapterHistory = new SearchAdapter();
        binding.rvHistoryRecycler.setAdapter(adapterHistory);
        adapterHistory.setOnItemClickInterface(this);

        binding.rvHotRecycler.setLayoutManager(new MyFlexboxLayoutManager(getActivity()));
        adapterHot = new SearchAdapter();
        binding.rvHotRecycler.setAdapter(adapterHot);
        adapterHot.setOnItemClickInterface(this);

        goodsAdapter = new HomeSearchGoodsAdapter();
        binding.rvGoodsRecycler.setLayoutManager(new MyGridLayoutManager(getActivity(), 2));
        binding.rvGoodsRecycler.setAdapter(goodsAdapter);


        binding.groupDefault.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                sort = 1;
                orderBy = 1;
                initSortView(sort);
                onGetData(1);
//                if (ppwDefault == null) {
//                    ppwDefault = new RecyclerViewPPW(getActivity(), null, -1) {
//                        @Override
//                        protected void initView(View mainView) {
//                            super.initView(mainView);
//                            RecyclerView recyclerView = ViewUtils.findViewById(mainView, R.id.recyclerView);
//                            if (recyclerView != null) {
//                                recyclerView.setPadding(DensityUtil.getDimens(R.dimen.dp_8), DensityUtil.getDimens(R.dimen.dp_8), 0, 0);
//                            }
//                            RoundLinearLayout rllPPWView = ViewUtils.findViewById(mainView, R.id.rllPPWView);
//                            if (rllPPWView != null) {
//                                rllPPWView.getDelegate().setCornerRadius(0);
//                                rllPPWView.getDelegate().setStrokeWidth(0);
//                            }
//                        }
//
//                        @Override
//                        public void onCreateViewHolder(PpwRecyclerItemBinding binding, BaseViewHolder viewHolder) {
//                            super.onCreateViewHolder(binding, viewHolder);
//                            ViewGroup.LayoutParams layoutParams = binding.groupItem.getLayoutParams();
//                            if (layoutParams != null) {
//                                layoutParams.height = DensityUtil.getDimens(R.dimen.dp_50);
//                                binding.groupItem.setLayoutParams(layoutParams);
//                            }
//
//                            binding.vLine.setVisibility(View.GONE);
//                        }
//
//                        @Override
//                        public void onItemClick(View view, BaseRVAdapter adapter, int onclickType, int position, ADInfo bean) {
//                            super.onItemClick(view, adapter, onclickType, position, bean);
//                            typeDefault = bean.getCount(); //0 默认 1 人气  2最新上架 3 评论
//                            binding.tvDefault.setText(bean.getImageContent());
//                            onGetData(1);
//                        }
//                    };
//                    //0 默认 1 人气  2最新上架 3 评论
//                    List<ADInfo> list = new ArrayList<>();
//
//                    ADInfo adInfo1 = new ADInfo();
//                    adInfo1.setImageName("默认排序");
//                    adInfo1.setImageContent("默认");
//                    adInfo1.setCount(0);
//                    list.add(adInfo1);
//
//                    ADInfo adInfo2 = new ADInfo();
//                    adInfo2.setImageName("按人气");
//                    adInfo2.setImageContent("人气");
//                    adInfo2.setCount(1);
//                    list.add(adInfo2);
//
//                    ADInfo adInfo3 = new ADInfo();
//                    adInfo3.setImageName("最新上架");
//                    adInfo3.setImageContent("最新");
//                    adInfo3.setCount(2);
//                    list.add(adInfo3);
//
//                    ADInfo adInfo4 = new ADInfo();
//                    adInfo4.setImageName("按评论");
//                    adInfo4.setImageContent("评论");
//                    adInfo4.setCount(3);
//                    list.add(adInfo4);
//
//                    ppwDefault.setDataList(list);
//
//                }
//                ppwDefault.showAsDropDown(binding.groupDefault);

            }
        });


        binding.tvSalesVolume.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                sort = 2;
                orderBy = 2;
                initSortView(sort);
                onGetData(1);
            }
        });

        binding.groupPrice.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                orderBy = orderBy == 1 ? 2 : 1;
                sort = 3;
                initSortView(sort);
                onGetData(1);
            }
        });

        binding.groupFilter.setVisibility(View.GONE);
        binding.groupFilter.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
//                binding.dlDrawerLayout.openDrawer(Gravity.RIGHT);
            }
        });


        binding.etSelectText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    binding.clView1.setVisibility(View.VISIBLE);
                    binding.clView2.setVisibility(View.GONE);
                    goodsAdapter.clear();
                }
            }
        });


        binding.clView1.setVisibility(View.VISIBLE);
        binding.clView2.setVisibility(View.GONE);
        binding.etSelectText.setText("");

        initSortView(sort);

        drawerAdapter = new HomeSearchDrawerAdapter();
        binding.rvDrawerLayoutRecycler.setLayoutManager(new MyLinearLayoutManager(this));
        binding.rvDrawerLayoutRecycler.setAdapter(drawerAdapter);

        viewUtils.setRefreshStateLayout(binding.rvGoodsRecycler, this, this);
        viewUtils.setAutoPreload(false);
    }


    @Override
    protected void initData(Intent intent) {
        super.initData(intent);
        if (isFirstLoading) {
            initHistoryDatas();
            /*
            viewModel.hotSearch().observe(this, new BaseViewObserver<LiveDataWrapper<HotSearchBean>>() {
                @Override
                protected void onSuccess(LiveDataWrapper<HotSearchBean> data) {
                    adapterHot.setDataList(data.data.getData());
                    isFirstLoading = false;
                }

                @Override
                public boolean isEmptyData(LiveDataWrapper<HotSearchBean> data) {
                    return UIUtils.isEmpty(data.data.getData());
                }


            });
            */

            if (drawerAdapter != null) {

                List<ADInfo> list = new ArrayList<>();
                ADInfo adInfo1 = new ADInfo();
                adInfo1.setImageName("热门筛选");
                adInfo1.setCount(0);
                list.add(adInfo1);

                ADInfo adInfo2 = new ADInfo();
                adInfo2.setImageName("品牌");
                adInfo2.setCount(1);
                list.add(adInfo2);

                ADInfo adInfo3 = new ADInfo();
                adInfo3.setImageName("适合年龄");
                adInfo3.setCount(2);
                list.add(adInfo3);

                ADInfo adInfo4 = new ADInfo();
                adInfo4.setImageName("主要配方");
                adInfo4.setCount(3);
                list.add(adInfo4);

                drawerAdapter.setDataList(list);
            }

        } else {
            onGetData(1);
        }

    }


    private void initSortView(int typeSort) {
        switch (typeSort) {
            case 1://默认的
                binding.ivDefault.setImageResource(R.mipmap.ic_triangle_down);
                binding.ivDefault.setRotation(0);
                binding.tvDefault.setTextColor(0xffFE7E11);
                binding.tvDefault.setTypeface(Typeface.DEFAULT_BOLD);


                binding.tvSalesVolume.setTextColor(0xff999999);
                binding.tvSalesVolume.setTypeface(Typeface.DEFAULT);


                orderBy = 1;
                binding.ivPriceTop.setImageResource(R.mipmap.ic_triangle_top);
                binding.ivPriceTop.setRotation(0);
                binding.ivPriceDown.setImageResource(R.mipmap.ic_triangle_top);
                binding.ivPriceDown.setRotation(180);
                binding.tvPrice.setTextColor(0xff999999);
                binding.tvPrice.setTypeface(Typeface.DEFAULT);


                break;
            case 2://销量
                binding.ivDefault.setImageResource(R.mipmap.ic_triangle_top);
                binding.ivDefault.setRotation(180);
                binding.tvDefault.setTextColor(0xff999999);
                binding.tvDefault.setTypeface(Typeface.DEFAULT);

                binding.tvSalesVolume.setTextColor(0xffFE7E11);
                binding.tvSalesVolume.setTypeface(Typeface.DEFAULT_BOLD);

                orderBy = 2;
                binding.ivPriceTop.setImageResource(R.mipmap.ic_triangle_top);
                binding.ivPriceTop.setRotation(0);
                binding.ivPriceDown.setImageResource(R.mipmap.ic_triangle_top);
                binding.ivPriceDown.setRotation(180);
                binding.tvPrice.setTextColor(0xff999999);
                binding.tvPrice.setTypeface(Typeface.DEFAULT);


                break;

            case 3://价格
                binding.ivDefault.setImageResource(R.mipmap.ic_triangle_top);
                binding.ivDefault.setRotation(180);
                binding.tvDefault.setTextColor(0xff999999);
                binding.tvDefault.setTypeface(Typeface.DEFAULT);

                binding.tvSalesVolume.setTextColor(0xff999999);
                binding.tvSalesVolume.setTypeface(Typeface.DEFAULT);

                binding.tvPrice.setTextColor(0xffFE7E11);
                binding.tvPrice.setTypeface(Typeface.DEFAULT_BOLD);

                // 排序(1升序 2降序)
                if (orderBy == 1) {
                    binding.ivPriceTop.setImageResource(R.mipmap.ic_triangle_down);
                    binding.ivPriceTop.setRotation(180);
                    binding.ivPriceDown.setImageResource(R.mipmap.ic_triangle_top);
                    binding.ivPriceDown.setRotation(180);
                } else {
                    binding.ivPriceTop.setImageResource(R.mipmap.ic_triangle_top);
                    binding.ivPriceTop.setRotation(0);
                    binding.ivPriceDown.setImageResource(R.mipmap.ic_triangle_down);
                    binding.ivPriceDown.setRotation(0);
                }
                break;
        }
    }


    @Override
    public void onGetData(int pn) {
        String text = binding.etSelectText.getText().toString().trim();
        if (UIUtils.isEmpty(text)) return;

        if (pn == 1) {
//            if (goodsAdapter != null) {
//                goodsAdapter.clear();
//            }
            hideSoftInput();
            binding.clView1.setVisibility(View.GONE);
            binding.clView2.setVisibility(View.VISIBLE);
        }
        //搜索参数
        searchParams.setPageno(pn);
        searchParams.setKeywords(text);
        searchParams.setOrderkey(sort);
        searchParams.setOrdertype(orderBy);

        if (UIUtils.isNotEmpty(userKey)) {
            searchParams.setUserkey(userKey);
        }

        viewModel.searchByKeyWord(searchParams)
                .observe(this, new BaseViewObserver<LiveDataWrapper<CateGoodsPageBean>>(viewUtils.getStateLayout()) {
                    @Override
                    protected void onSuccess(LiveDataWrapper<CateGoodsPageBean> data) {
                        //搜索到 商品

                        viewUtils.setDataListRefreshLayout(goodsAdapter, searchParams.getPageno(), searchParams.getPagesize(), data.data.getProduct());
//                goodsAdapter.setDataList( new ArrayList<SearchGoodsBean.RecordsBean>() );
                    }

                    @Override
                    public boolean isEmptyData(LiveDataWrapper<CateGoodsPageBean> data) {
                        return searchParams.getPageno() == 1 && UIUtils.isEmpty(data.data.getProduct());
                    }

                    @Override
                    public boolean isRefreshLayoutData() {
                        return true;
                    }
                });


    }


    @Override
    public boolean onItemClick(View view, int onclickType, int itemType, int position, Object bean) {
        HotSearchBean.DataBean dataBean = (HotSearchBean.DataBean) bean;
        addHistory(dataBean);
        binding.etSelectText.setText(dataBean.getTitle());
        binding.etSelectText.requestFocus();
        binding.etSelectText.setSelection(dataBean.getTitle().length());
        onGetData(1);
        return true;
    }

    private void initHistoryDatas() {
        List<HotSearchBean.DataBean> listHistory = SPUtils.getList(AppConstants.SpKey.HISTORY_SEARCH, HotSearchBean.DataBean.class);
        if (UIUtils.isEmpty(listHistory)) {
            binding.gHistory.setVisibility(View.GONE);
        } else {
            binding.gHistory.setVisibility(View.VISIBLE);
            adapterHistory.setDataList(listHistory);
        }
    }

    public void clearHistory() {
        adapterHistory.clear();
        SPUtils.putBean(AppConstants.SpKey.HISTORY_SEARCH, new ArrayList<>());
        binding.gHistory.setVisibility(View.GONE);
    }

    public void addHistory(HotSearchBean.DataBean dataBean) {
        int pos = adapterHistory.getPosition(dataBean);
        if (pos > -1) {
            adapterHistory.move(pos, 0);
        } else {
            if (adapterHistory.getChildCount() >= 8) {
                adapterHistory.remove(adapterHistory.getLastPosition());
            }
            adapterHistory.add(0, dataBean);
            adapterHistory.notifyDataSetChanged();
        }
        ArrayList list = adapterHistory.getDatas();
        SPUtils.putBean(AppConstants.SpKey.HISTORY_SEARCH, list);
        if (binding.gHistory.getVisibility() == View.GONE) {
            binding.gHistory.setVisibility(View.VISIBLE);
        }
    }


}
